home *** CD-ROM | disk | FTP | other *** search
- Path: erich.triumf.ca!bennett
- From: bennett@erich.triumf.ca (P.Bennett)
- Newsgroups: comp.lang.c
- Subject: Re: scanf/gets interaction ?
- Date: 25 Mar 1996 10:10 PST
- Organization: TRIUMF: Tri-University Meson Facility
- Distribution: world
- Message-ID: <25MAR199610104015@erich.triumf.ca>
- References: <4j6joa$6ve@muller.loria.fr>
- NNTP-Posting-Host: ftp.triumf.ca
- News-Software: VAX/VMS VNEWS 1.50
-
- In article <4j6joa$6ve@muller.loria.fr>, roegel@loria.fr (Denis B. Roegel) writes...
- >I have the following program:
- >
- >#include <stdio.h>
- >
- >main(){
- >int n;
- >char num[10];
- >char*r;
- >fflush(stdin);
-
- fflush() is undefined on input streams.
-
- >printf("n: ");scanf("%i",&n);
- >printf("Numero ? ");r = gets(num);
- >printf("Bien recu!\n");
- >}
- >
- >which I compile with gcc on SunOS. The program asks for a first number n which
- >I enter. But I never get a chance of entering a second one. Why is this so ?
-
- scanf() leaves the '\n' in the input buffer, which gets() sees as the next
- entry. Don't mix scanf() and gets() calls! (In fact _don't_ use gets() at all
- - use fgets() instead - butt you still have the same problem...)
-
- scanf() is very bad for direct user input - if it's looking for a number, and
- the user enters a letter, scanf() leaves the letter in the input stream, and
- you can never recover...
-
- A better way to handle input is to use fgets() to get a line into a buffer,
- then you can check for valid input, and use sscanf() or other functions to
- convert the input as needed.
-
- Peter Bennett VE7CEI | Vessels shall be deemed to be in sight
- Internet: bennett@triumf.ca | of one another only when one can be
- Packet: ve7cei@ve7kit.#vanc.bc.ca | observed visually from the other
- TRIUMF, Vancouver, B.C., Canada | ColRegs 3(k)
- GPS and NMEA info and programs: ftp://sundae.triumf.ca/pub/peter/index.html
- or: ftp://ftp-i2.informatik.rwth-aachen.de/pub/arnd/GPS/peter/index.html
-
-